<?php
/**
 * Created by PhpStorm.
 * User: tebibit
 * Date: 2016/3/14
 * Time: 9:07
 */

namespace Manage\Controller;


class NewsController extends CommonController {

    private $api;
    private $user;

    protected function _initialize(){
        $login = A('Login');
        if( ! session($login::SESSION_NAME) ) $this->error('请先登录', U('Login/Index'));
        $this->api  = A('Api/Request');
        $this->user = session($login::SESSION_NAME);
    }

    /**
     * 新闻列表
     */
    public function Lists(){

        $do = I('get.do');

        switch($do) {
            case 'add':
                if( IS_POST ){
                    $post  = I('post.');
                    $image = $this->_upload();
                    if($image){
                        $data['news_image']    = trim($image);
                    } else {
                        $data['news_image']    = trim($post['news_image_url']);
                    }
                    $data['news_title']        = trim($post['news_name']);
                    $data['news_class_id']     = trim($post['cid']);
                    $data['news_introduction'] = trim($post['introduction']);
                    $data['news_content']      = trim($post['news_content']);
                    $data['news_link']         = trim($post['news_link']);
                    $data['news_desc']         = trim($post['news_sort']);
                    if(empty($data['news_desc'])) $data['news_desc'] = 0;
                    $data['isposition']        = trim($post['isposition']);
                    if($data['isposition'] == 1) $this->_fm_isposition($data['news_class_id']);
                    $data['news_time_add']     = $data['news_time_update'] = time();
                    $data['news_user_add']     = $data['news_user_update'] = 58;
                    $result = $this->_newsdo('add',0,$data);
                    $result == 1 ? $this->success('添加成功', U('News/Lists')) : $this->error('添加失败', U('News/Lists'));
                }else {
                    $category = $this->_getcategory();
                    $this->assign('category', $category);
                    $this->display('News');
                }
                break;

            case 'edit':
                if( IS_POST ){
                    $post  = I('post.');
                    $c_url = $post['c_url'];
                    $id    = trim($post['id']);
                    $image = $this->_upload();
                    if($image){
                        $data['news_image']    = trim($image);
                    } else {
                        $data['news_image']    = trim($post['news_image_url']);
                    }
                    $data['news_title']        = trim($post['news_name']);
                    $data['news_class_id']     = trim($post['cid']);
                    $data['news_introduction'] = trim($post['introduction']);
                    $data['news_content']      = trim($post['news_content']);
                    $data['news_link']         = trim($post['news_link']);
                    $data['news_desc']         = trim($post['news_sort']);
                    if(empty($data['news_desc'])) $data['news_desc'] = 0;
                    $data['isposition']        = trim($post['isposition']);
                    if($data['isposition'] == 1) $this->_fm_isposition($data['news_class_id']);
                    $data['news_time_update']  = time();
                    $data['news_user_add']     = $data['news_user_update'] = 58;
                    $result = $this->_newsdo('edit',$id,$data);
                    $result == 1 ? $this->success('修改成功',$c_url) : $this->error('修改失败', U('News/Lists'));
                }else {
                    $c_url = I('get.curl');
                    $gid   = (int)I('get.id');
                    if( $gid <= 0  ) exit();
                    if( ! $gid ) $this->error('请选择要编辑的新闻', U('News/Lists'));
                    $news  = $this->_newsdo('find',$gid);
                    $news['isposition'] = $news['isposition'] == 1 ? 'checked' : '';
                    $category = $this->_getcategory();
                    //为栏目数组添加一个是否选中的元素
                    foreach($category as $k => $v){
                        if($category[$k]['common_class_id'] == $news['news_class_id']) $category[$k]['selected'] = 'selected';
                    }
                    $this->assign('c_url', $c_url);
                    $this->assign('category', $category);
                    $this->assign('news', $news);
                    $this->display('News');
                }
                break;

            case 'delete':
                $gid    = (int)I('get.id');
                if( ! $gid > 0 ) $this->error('非法操作', U('News/Lists'));
                $result = $this->_newsdo('del',$gid);
                $result == 1 ? $this->success('删除成功') : $this->error('删除失败');
                break;

            case 'sort':
                $this->_sort();
                break;

            default:
                $c_url     = $this->_current_url();
                $get       = I('get.');
                $cid       = $get['cid'];
                $keyword   = $get['keyword'];
                if(empty($cid)){
                    $cid   = null;
                } else {
                    $issort = 1;
                }
                if(empty($keyword)) $keyword = null;

                $nowpage   = (int)$get['page'];
                $page      = $nowpage > 0 ? $nowpage : 1;
                $pagesize  = C('LIST_PAGE_SIZE');
                $count     = $this->_getnewslist($cid,$keyword);
                $total     = count($count);
                $vlist     = $this->_getnewslist($cid,$keyword,$page,$pagesize);

                for($i=0;$i<count($vlist);$i++){
                    $cate = $this->_getcategory($vlist[$i]['news_class_id']);
                    $vlist[$i]['news_class_name'] = $cate[0]['common_class_name'];
                    $vlist[$i]['isposition'] = $vlist[$i]['isposition'] == 1 ? 'checked' : '';

                }

                $category  = $this->_getcategory();
                //为栏目数组添加一个是否选中的元素
                if($cid){
                    foreach($category as $k => $v){
                        if($category[$k]['common_class_id'] == $cid) $category[$k]['selected'] = 'selected';
                    }
                }

                $this->assign('issort', $issort);
                $this->assign('c_url', $c_url);
                $this->assign('cid', $cid);
                $this->assign('keyword', $keyword);
                $this->assign('category', $category);
                $this->assign('total', $total);
                $this->assign('pagesize', $pagesize);
                $this->assign('pages', ceil($total/$pagesize));
                $this->assign('vlist', $vlist);
                $this->display('Index');
                break;
        }
    }

    //由id查询栏目信息，如果id为空查询所有
    private function _getcategory($id=null){
        $where['common_class_sort'] = 'LB0004';
        if($id!=null) $where['common_class_id'] = $id;
        $result = zyt_data_init()->table('common_class')->where($where)->select();
        return $result;
    }

    //查询新闻列表
    private function _getnewslist($cid=null,$keyword=null,$page=null,$pagesize=null){
        $orders = 'isposition DESC, news_desc DESC, news_time_update DESC';

        if($cid!=null)   $where['news_class_id'] = $cid;
        if($keyword!=null)  $where['news_title'] = array('LIKE', '%'.$keyword.'%');

        $result = zyt_data_init()->table('news')->where($where)->page($page,$pagesize)->order($orders)->select();
        return $result;
    }

    //对新闻添加、修改、删除、查询的统一方法
    private function _newsdo($type,$id=null,$data=null){
        $db = zyt_data_init()->table('news');
        switch($type){
            default:
                $result = $this->error('操作错误');
                break;
            case 'add':
                if($data == null) $this->error('操作错误');
                $result = $db->data($data)->add();
                break;
            case 'edit':
                if($id == null) $this->error('操作错误');
                $result = $db->data($data)->where('news_id='.$id)->save();
                break;
            case 'del':
                if($id == null) $this->error('操作错误');
                $result = $db->where('news_id='.$id)->delete();
                break;
            case 'find':
                if($id == null) $this->error('操作错误');
                $result = $db->where('news_id='.$id)->find();
                break;
        }
        return $result;

    }

    //新闻排序处理
    private function _sort(){
        $post       = I('post.');
        $sorts      = $post['sort'];
        $news_id    = $post['news_id'];
        $isposition = (int)$post['isposition'];

        if(empty($news_id)) {
            $this->error('请选择要更新排序的新闻');
        }

        $this->_isposition($isposition);

        $sql = 'UPDATE [sso_news] SET [news_desc] = CASE news_id ';
        foreach( $news_id as $id ){
            $sort = (int)$sorts[$id];
            if( $sort >= 0 ){
                $sql .= ' WHEN ' . $id . ' THEN ' . $sort;
            }
        }
        $in = implode(',', $news_id);
        $sql .= ' END WHERE news_id IN (' . $in .')';

        $db = zyt_data_init();
        $result = $db->query($sql);

        if( $result->rowCount() > 0 ){
            $this->success('更新成功');
        }else{
            $this->error('更新失败');
        }
    }

    //图片上传
    private function _upload(){
        $config   = C( 'UPLOAD_CONFIG');
        $upload   = new \Think\Upload($config);// 实例化上传类
        $string   = $config['rootPath'];
        $rootPath = preg_replace('/(^.)/', '', $string);

        // 上传文件
        $info     = $upload->upload();
        foreach ($info as $file){
            $result = "http://" . $_SERVER['SERVER_NAME'] . $rootPath . $file['savepath'] . $file['savename'];
        }
        return $result;
    }

    //获取url
    private function _current_url(){
        $c_url = urlencode("http://" . $_SERVER['SERVER_NAME'] .$_SERVER['REQUEST_URI']);
        return $c_url;
    }

    //推荐字段修改
    private function _isposition($id){
        $db    = zyt_data_init();
        $cdata = $db->table('news')->where('news_id='.$id)->find();
        $cid   = (int)$cdata['news_class_id'];
        $this->_fm_isposition($cid);
        $data['isposition'] = 1;
        $result = $db->table('news')->data($data)->where('news_id='.$id)->save();
        if($result != 1) $this->error('推荐修改失败');
    }

    //初始化同一栏目的推荐字段
    private function _fm_isposition($cid){
        $data['isposition'] = 0;
        $result = zyt_data_init()->table('news')->data($data)->where('news_class_id='.$cid)->save();
        if($result == 0) $this->error('推荐初始化失败');
    }
}
